import { getInfo } from '@/api/sys/user'
import { login, logout } from '@/api/sys/account'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'

const state = {
  token: getToken(),
  uid: 0,
  nickname: '',
  avatar: '',
  profile: '',
  roles: [],
  decryption: ''
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_PROFILE: (state, profile) => {
    state.profile = profile
  },
  SET_NICKNAME: (state, nickname) => {
    state.nickname = nickname
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_UID: (state, uid) => {
    state.uid = uid
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_DECRYPTION: (state, decryption) => {
    state.decryption = decryption
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ account: username.trim(), password: password })
        .then(response => {
          const { result } = response
          commit('SET_TOKEN', result)
          setToken(result)
          resolve()
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token)
        .then(response => {
          const { result } = response

          if (!result) {
            reject('Verification failed, please Login again.')
          }

          const { id, nickname, avatar, profile } = result

          commit('SET_UID', id)
          commit('SET_NICKNAME', nickname)
          commit('SET_AVATAR', avatar)
          commit('SET_PROFILE', profile)

          resolve(result)
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token)
        .then(() => {
          commit('SET_TOKEN', '')
          removeToken()
          resetRouter()
          resolve()
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      removeToken()
      resolve()
    })
  },

  setDecryption({ commit }, decryption) {
    commit('SET_DECRYPTION', decryption)
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
